import BaseBusinessController from './../base/BaseBusinessController'
import _ from "lodash";
import { Op } from 'sequelize'

/**
 * 普通用户
 */
class UserController extends BaseBusinessController {

    /**
     * 获取用户信息
     * @returns {Promise.<*>}
     */
    async actionGet() {
        let { open_id } = $_POST
        if (!open_id) {
            throw new Error("参数缺失");
        }

        return await this.modules("User").where({ open_id }).joinWith(['Company']).first();
    }

    /**
     * 获取用户信息
     * @returns {Promise.<*>}
     */
    async actionInfo() {
        let { open_id } = $_POST
        if (!open_id) {
            throw new Error("参数缺失");
        }

        return await this.modules("User").where({ open_id }).joinWith(['Company']).first();
    }
    /**
     * 获取用户信息
     * @returns {Promise.<*>}
     */
    async actionInfoByUserid() {
        let { userid } = $_POST
        if (!userid) {
            throw new Error("参数缺失");
        }

        return await this.modules("User").where({ id:userid }).joinWith(['Company']).first();
    }


    /**
     * 用户列表集合
     * @returns {Promise<*|Object[]>}
     */
    async actionList() {
        let { number, size } = super._getPage();

        let { search, company_id, live_province, live_city, live_area, live_street } = $_POST
        let where = {}
        if (search) {
            where = {
                [Op.or]: [{
                        real_name: {
                            [Op.like]: '%' + $_POST['search'] + '%'
                        }
                    },
                    {
                        id_card: {
                            [Op.like]: '%' + $_POST['search'] + '%'
                        }
                    }
                ]
            }
        }

        if (live_province) {
            where = {
                [Op.and]: [
                    where,
                    { live_province }
                ]
            }
        }
        if (live_city) {
            where = {
                [Op.and]: [
                    where,
                    { live_city }
                ]
            }
        }
        if (live_area) {
            where = {
                [Op.and]: [
                    where,
                    { live_area }
                ]
            }
        }
        if (live_street) {
            where = {
                [Op.and]: [
                    where,
                    { live_street }
                ]
            }
        }

        if (company_id) {
            where = {
                [Op.and]: [
                    where,
                    { company_id }
                ]
            }
        }


        P(where)

        let users = await this.modules('User').where(where).page(number, size).order([
            ['id', 'DESC']
        ]).select(false, { raw: true });

        // P(users)
        for (let user of users.children) {
            if (user.company_id) {
                let company = await this.modules('Company').where({ id: user.company_id }).first();

                user['company'] = company
                let roomResult = await db.sql('select GROUP_CONCAT(name) as room from hz_building_room where company_id = :company_id', { company_id: user.company_id })
                user['room'] = roomResult[0].room

                if (company) {
                    user['building'] = await this.modules('Building').where({ id: company.building_id }).first();
                }
            }
        }
        return users;
    }


    async actionRemove() {
        let { id } = $_POST
        let user = await this.modules('User').where({ id }).first();
        if (!user) {
            throw new Error("用户未找到")
        }

        let t = await db.transaction();
        try {
            /**
             * 删除用户
             */
            await this.modules('User').where({ id }).destroy({ transaction: t });
            await t.commit();
            return true;
        } catch (error) {
            await t.rollback();
            throw new Error("删除失败");
        }

    }

    /**
     * 普通公司员工信息录入
     * company_id 码自带
     * open_id 微信小程序openId
     * real_name 真实姓名
     * mobile, 手机号
     * id_card, 身份证号
     * card_province, 户籍省
     * card_city, 户籍市
     * card_area, 户籍区
     * card_street, 户籍街道
     * card_address, 户籍详细地址
     * live_province, 现住址省
     * live_city,现住址市
     * live_area, 现住址区
     * live_street,现住址街道
     * live_address, 现住址详细地址
     * card_bck, 身份证国徽面
     * card_pre, 身份证人像面
     * head  人脸
     * @returns {Promise<void>}
     */
    async actionAddOrUpdate() {
        let {
            company_id,
            open_id,
            real_name,
            mobile,
            id_card,
            card_province,
            card_city,
            card_area,
            card_street,
            card_address,
            avatarUrl,
            live_province,
            live_city,
            live_area,
            live_street,
            live_address,
            card_bck,
            card_pre,
            face_option,
            head
        } = $_POST

        //验证公司
        await super.validateRealName(real_name);
        await super.validateMobile(mobile);
        await super.validateOpenId(open_id);
        if (company_id) {
            await super.validateCompany(company_id);
            // await super._validateAddress(card_province, card_city, card_area, card_street);
            // await super._validateAddress(live_province, live_city, live_area, live_street);
        }
        await super.validateIdCard(id_card, card_bck, card_pre);

        let user = await this.modules("User").where({ open_id }).first();
        if (user) {
            if (user['company_id'] && $_POST['company_id'] && user['company_id'] !== $_POST['company_id']) {
                throw new Error("请先离开原公司")
            }
            /**
             * 更新逻辑
             */
            //delete $_POST['company_id']
            await this.modules("User").where({ open_id }).update($_POST);
            return true;
        } else {
            /**
             * 新增逻辑
             */
            await this.modules("User").where({ open_id }).validateCreate($_POST)
            return true;
        }
        return true;
    }
}

export default UserController;